@file:Suppress("unused")

package com.lixinkeji.extension

import android.R
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Build
import android.util.DisplayMetrics
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.core.app.NotificationManagerCompat
import androidx.fragment.app.FragmentActivity
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.drake.logcat.LogCat
import com.drake.net.utils.scope
import com.drake.net.utils.scopeDialog
import com.drake.tooltip.dialog.BubbleDialog
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.lixinkeji.data.CityJsonBean
import com.lixinkeji.data.LoadCityBean
import com.lixinkeji.utils.SoftKeyBroadManager
import java.io.BufferedReader
import java.io.InputStreamReader


/**
 * Activity extensions
 *
 * @author Classic
 * @version v1.0, 2019-05-20 15:48
 */
fun Activity.start(cls: Class<out Activity>) {
    startActivity(Intent(this, cls))
    overridePendingTransition(0, 0)
}

fun Activity.start(cls: Class<out Activity>, intent: (Intent.() -> Unit) = {}) {
    val intent1 = Intent(this, cls)
    intent(intent1)
    startActivity(intent1)
    overridePendingTransition(0, 0)
}

fun Activity.startCode(cls: Class<out Activity>, intent: (Intent.() -> Unit) = {}) {
    startActivityForResult(Intent(this, cls).apply(intent), 200)
    overridePendingTransition(0, 0)
}

fun Activity.finish(code: Int, intent: (Intent.() -> Unit) = {}) {
    setResult(code, Intent().apply(intent))
    finish()
    overridePendingTransition(0, 0)
}

fun Activity.getIntentString(name: String): String {
    val stringExtra = intent.getStringExtra(name)
    return if (stringExtra.isNullOrEmpty()) {
        ""
    } else stringExtra
}

fun Activity.getIntentDouble(name: String, defaultValue: Double = 0.00): Double {
    return intent.getDoubleExtra(name, defaultValue)
}

fun Activity.getIntentBoolean(name: String, defaultValue: Boolean = false): Boolean {
    return intent.getBooleanExtra(name, defaultValue)
}

fun Activity.getIntentInt(name: String, defaultValue: Int = -1): Int {
    return intent.getIntExtra(name, defaultValue)
}

fun Activity.getIntentLong(name: String, defaultValue: Long = 0L): Long {
    return intent.getLongExtra(name, defaultValue)
}

fun <T> Activity.getIntentSerializable(name: String): T {
    return intent?.getSerializableExtra(name)?.let { it as T }!!
}

/**
 * 显示软键盘
 */
fun Activity.showKeyboard(view: View?) {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

/**
 * 关闭软键盘
 * @receiver Activity
 * @param view View?
 */
fun Activity.hideKeyboard(view: View?) {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view?.windowToken, 0)
    // imm.hideSoftInputFromWindow(view?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

/**
 * 屏幕宽
 * @receiver Activity
 * @return Int
 */
fun Activity.screenWidth(): Int {
    val metrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.widthPixels
}

/**
 * 屏幕高
 * @receiver Activity
 * @return Int
 */
fun Activity.screenHeight(): Int {
    val metrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.heightPixels
}

fun Activity.fullScreen() {
    window.setFlags(
        WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN
    )
}

/**
 * 状态栏透明
 * @receiver Activity
 */
fun Activity.makeStatusBarTransparent() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        window.apply {
            clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            } else {
                decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            }
            statusBarColor = Color.TRANSPARENT
        }
    }
}

fun Activity.isDestroy() = isFinishing || isDestroyed

val Activity.sharedPreferences: SharedPreferences
    get() = getSharedPreferences(
        "config",
        Context.MODE_PRIVATE
    )
var Activity.isLogin: Boolean
    get() = sharedPreferences["isLogin", false]!!
    set(value) = sharedPreferences.set("isLogin", value)
var Activity.isFirstOpen: Boolean
    get() = sharedPreferences["isFirstOpen", true]!!
    set(value) = sharedPreferences.set("isFirstOpen", value)
var Activity.nameClickTip: Boolean
    get() = sharedPreferences["nameClickTip", true]!!
    set(value) = sharedPreferences.set("nameClickTip", value)

var Activity.nameClickTipOther: Boolean
    get() = sharedPreferences["nameClickTipOther", true]!!
    set(value) = sharedPreferences.set("nameClickTipOther", value)

var Activity.squareFloat2Flag: Boolean
    get() = sharedPreferences["squareFloat2Flag", false]!!
    set(value) = sharedPreferences.set("squareFloat2Flag", value)

var Activity.token: String
    get() = sharedPreferences["token", ""]!!
    set(value) = sharedPreferences.set("token", value)

var Activity.phoneNumber: String
    get() = sharedPreferences["phoneNumber", ""]!!
    set(value) = sharedPreferences.set("phoneNumber", value)


var Activity.im_isLogin: Boolean
    get() = sharedPreferences["im_isLogin", false]!!
    set(value) = sharedPreferences.set("im_isLogin", value)

//var Activity.isSelectHeadImg: Boolean
//    get() = sharedPreferences["isSelectHeadImg", false]!!
//    set(value) = sharedPreferences.set("isSelectHeadImg", value)

var Activity.office_building: String
    get() = sharedPreferences["office_building", ""]!!
    set(value) = sharedPreferences.set("office_building", value)

var Activity.set_building_finish: Boolean
    get() = sharedPreferences["set_building_finish", false]!!
    set(value) = sharedPreferences.set("set_building_finish", value)

var Activity.user_latitude: String
    get() = sharedPreferences["user_latitude", ""]!!
    set(value) = sharedPreferences.set("user_latitude", value)

var Activity.user_longitude: String
    get() = sharedPreferences["user_longitude", ""]!!
    set(value) = sharedPreferences.set("user_longitude", value)

var Activity.uId: String
    get() = sharedPreferences["uId", ""]!!
    set(value) = sharedPreferences.set("uId", value)
var Activity.isAuthCode: Int
    get() = sharedPreferences["isAuthCode", 0]!!
    set(value) = sharedPreferences.set("isAuthCode", value)

var Activity.is_notif: String
    get() = sharedPreferences["is_notif", ""]!!
    set(value) = sharedPreferences.set("is_notif", value)
var Activity.is_onsin: String
    get() = sharedPreferences["is_onsin", "0"]!!
    set(value) = sharedPreferences.set("is_onsin", value)

var Activity.is_clock: String
    get() = sharedPreferences["is_clock", "0"]!!
    set(value) = sharedPreferences.set("is_clock", value)

var Activity.img_url: String
    get() = sharedPreferences["img_url", ""]!!
    set(value) = sharedPreferences.set("img_url", value)
var Activity.itemPosition: Int
    get() = sharedPreferences["itemPosition", -1]!!
    set(value) = sharedPreferences.set("itemPosition", value)
var Activity.lastPosition: Int
    get() = sharedPreferences["lastPosition", -1]!!
    set(value) = sharedPreferences.set("lastPosition", value)

var Activity.selectPosition: Int
    get() = sharedPreferences["selectPosition", -1]!!
    set(value) = sharedPreferences.set("selectPosition", value)

var Activity.name: String
    get() = sharedPreferences["name", ""]!!
    set(value) = sharedPreferences.set("name", value)


var Activity.industryId: String
    get() = sharedPreferences["industryId", ""]!!
    set(value) = sharedPreferences.set("industryId", value)

var Activity.workAreaId: String
    get() = sharedPreferences["workAreaId", ""]!!
    set(value) = sharedPreferences.set("workAreaId", value)

var Activity.customBuilding: String
    get() = sharedPreferences["customBuilding", ""]!!
    set(value) = sharedPreferences.set("customBuilding", value)


var Activity.clickItemPosition: Int
    get() = sharedPreferences["clickItemPosition", -1]!!
    set(value) = sharedPreferences.set("clickItemPosition", value)


val Activity.isInputOpen: Boolean
    get() = SoftKeyBroadManager((findViewById<ViewGroup>(R.id.content)).getChildAt(0)).isSoftKeyboardOpened

/**
 * 选择音乐文件
 * @receiver Activity
 * @param code Int
 */
fun Activity.startMusic(code: Int) {
    startActivityForResult(Intent(Intent.ACTION_GET_CONTENT).also {
        it.type = "audio/mpeg"//音频文件
        it.addCategory(Intent.CATEGORY_OPENABLE)
    }, code)
}

/**
 * 显示城市
 * @receiver FragmentActivity
 * @param callback Function3<[@kotlin.ParameterName] String, [@kotlin.ParameterName] String, [@kotlin.ParameterName] String, Unit>
 */
fun FragmentActivity.cityPickView(
    level: Int? = 2,
    callback: (province: String, city: String, area: String) -> Unit
) {
    scopeDialog(BubbleDialog(this, "")) {
        val loadCityBean = async {
            val json = getAsset("province.json")
            val provinces = arrayListOf<String>()
            val cities = arrayListOf<ArrayList<String>>()
            val areas = arrayListOf<ArrayList<ArrayList<String>>>()

            GSON.fromJson<List<CityJsonBean>>(json).forEach { province ->
                provinces.add(province.name)
                val cityArray = arrayListOf<String>()
                val provinceAreaArray = arrayListOf<ArrayList<String>>()
                province.city.forEach { city ->
                    cityArray.add(city.name)
                    val cityAreaArray = arrayListOf<String>()
                    if (city.area.isNullOrEmpty()) {
                        cityAreaArray.add("")
                    } else {
                        city.area.forEach { area ->
                            cityAreaArray.add(area)
                        }
                        provinceAreaArray.add(cityAreaArray)
                    }
                }
                cities.add(cityArray)
                areas.add(provinceAreaArray)
            }
            LoadCityBean(provinces, cities, areas)
        }.await()
        val optionView = OptionsPickerBuilder(
            this@cityPickView
        ) { options1, options2, options3, v ->
            when (level) {
                1 -> callback.invoke(loadCityBean.provinces[options1], "", "")
                2 -> callback.invoke(
                    loadCityBean.provinces[options1],
                    loadCityBean.cities[options1][options2],
                    ""
                )

                else -> callback.invoke(
                    loadCityBean.provinces[options1],
                    loadCityBean.cities[options1][options2],
                    loadCityBean.areas[options1][options2][options3]
                )
            }
        }.setLineSpacingMultiplier(2.0f)//条目间距
            .setSubmitColor(Color.WHITE)//确定按钮文字颜色
            .setCancelColor(Color.WHITE)//取消按钮文字颜色
            .setTitleSize(17)//标题文字大小
            .setSubCalSize(15)//取消，确定文字大小
            .setContentTextSize(17)//内容大小
            .setTitleText("选择地区")
            .setTitleColor(Color.WHITE)
            .setTitleBgColor(Color.parseColor("#1A1A1A"))
            .setDividerColor(Color.parseColor("#1AFFFFFF"))
            .setTextColorCenter(Color.WHITE) //设置选中项文字颜色
            .setTextColorOut(Color.parseColor("#FFFFFF"))
            .setBgColor(Color.parseColor("#1A1A1A"))
            .build<Any>()
        when (level) {
            1 -> optionView.setPicker(loadCityBean.provinces.toList())
            2 -> optionView.setPicker(loadCityBean.provinces.toList(), loadCityBean.cities.toList())
            else -> optionView.setPicker(
                loadCityBean.provinces.toList(),
                loadCityBean.cities.toList(),
                loadCityBean.areas.toList()
            )
        }
        optionView.show()
    }

}

/**
 * 性别选择
 * @receiver FragmentActivity
 * @param callback Function1<String, Unit>
 */
fun FragmentActivity.sexPickView(callback: (String) -> Unit) {
    scope {
        val sexList = arrayListOf("男", "女")
        val optionView = OptionsPickerBuilder(
            this@sexPickView
        ) { options1, options2, options3, v ->
            callback.invoke(
                sexList[options1]
            )
        }.setLineSpacingMultiplier(2.0f)//条目间距
            .setSubmitColor(Color.WHITE)//确定按钮文字颜色
            .setCancelColor(Color.WHITE)//取消按钮文字颜色
            .setTitleSize(17)//标题文字大小
            .setSubCalSize(15)//取消，确定文字大小
            .setContentTextSize(17)//内容大小
            .setTitleText("选择性别")
            .setTitleColor(Color.WHITE)
            .setTitleBgColor(Color.parseColor("#1A1A1A"))
            .setDividerColor(Color.parseColor("#1AFFFFFF"))
            .setTextColorCenter(Color.WHITE) //设置选中项文字颜色
            .setTextColorOut(Color.parseColor("#FFFFFF"))
            .setBgColor(Color.parseColor("#1A1A1A"))
            .build<Any>()
        optionView.setPicker(
            sexList.toList()
        )
        optionView.show()
    }
}

/**
 * 获取asset目录指定文件的内容
 * @receiver Activity
 * @param fileName String
 * @return String
 */
fun Activity.getAsset(fileName: String): String {
    try {
        assets?.apply {
            assets.list("")?.forEach {
                if (it.equals(fileName)) {
                    val stringBuilder = StringBuilder()
                    val buffer = BufferedReader(InputStreamReader(assets.open(fileName)))
                    buffer.readLines().forEach {
                        stringBuilder.append(it)
                    }
                    return stringBuilder.toString()
                }
            }
        }
    } catch (e: Exception) {
        LogCat.e(e)
    }
    return ""
}

/**
 * 申请权限
 * @receiver Activity
 * @param permissions [@kotlin.ExtensionFunctionType] Function1<ArrayList<String>, Unit> 权限列表
 * @param onGranted Function2<MutableList<String>, Boolean, Unit> 成功回调
 * @param onDenied Function2<MutableList<String>, Boolean, Unit> 失败回调
 */
fun Activity.requestPerm(
    permissions: ArrayList<String>.() -> Unit,
    onGranted: (MutableList<String>, Boolean) -> Unit,
    onDenied: (MutableList<String>, Boolean) -> Unit
) {
    val xxPermissions = XXPermissions.with(this)
    ArrayList<String>().apply(permissions).forEach {
        xxPermissions.permission(it)
    }
    xxPermissions.request(object : OnPermissionCallback {
        override fun onGranted(
            permissions: MutableList<String>,
            all: Boolean
        ) {
            onGranted.invoke(permissions, all)
        }

        override fun onDenied(
            permissions: MutableList<String>,
            never: Boolean
        ) {
            if (never) {
                toast("被永久拒绝授权，请手动授予读写权限")
                // 如果是被永久拒绝就跳转到应用权限系统设置页面
                XXPermissions.startPermissionActivity(
                    this@requestPerm,
                    permissions
                )
            } else {
                toast("获取权限失败")
            }
            onDenied.invoke(permissions, never)
        }
    })
}

/**
 * 判断是否打开通知权限
 * @receiver Activity
 * @return Boolean
 */
fun Activity.hasNotificationManager(): Boolean {
    return NotificationManagerCompat.from(this).areNotificationsEnabled()
}

/**
 * 跳转通知管理  是用于Android8及以上
 * @receiver Activity
 */
fun Activity.openNotificationManager() {
    val intent = Intent()
    intent.action = "android.settings.APP_NOTIFICATION_SETTINGS";
    intent.putExtra("app_package", packageName)
    intent.putExtra("app_uid", applicationInfo.uid)
    // for Android 8 and above
    intent.putExtra("android.provider.extra.APP_PACKAGE", packageName);
    startActivity(intent)
}






